using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;

namespace Rensselaer_Event_Finder.Hibernate.DAO
{
    
     /// The service that facilitates interaction between the database
     /// and the application for the User class
     
    public class UserDAO : GenericNHibernateDAO<User,int>
    {
        /// <summary>
        /// Make the entity persistent. It will be inserted or updated in the database 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        new public User save(User entity)
        {
            if (entity.Id == 0)
            {
                Globals.getWebService().saveUser(Globals.sanitizeSQL(entity.Username), Globals.sanitizeSQL(entity.Password));
                Globals.syncDatabase();
                entity = getByUsername(entity.Username);
            }
            if (entity.Events != null)
            {
                foreach (Event e in entity.Events)
                {
                    Globals.getWebService().saveRSVP(entity.Id, e.Id);
                }
            }
            Globals.syncDatabase();
            return entity;
        }
        /// <summary>
        /// create a query out of the username to obtain the user object
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>

        public User getByUsername(String username)
        {
            try
            {
                IQuery q = Session.GetNamedQuery("User.byUsername");
                q.SetString("username", username);
                return q.List<User>()[0];
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        /// Attempt to login the user if the username exists and the password is correct
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>

        public User login(String username, String password)
        {
            User u = getByUsername(username);
            if (u == null) return null;
            if (u.Password == password)
            {
                return u;
            }
            return null;
        }

    }
}
